<template>
  <el-input
    v-model="typeState.filterText"
    placeholder="按名称进行搜索"
    clearable
  />
  <el-tree
    class="filter-tree"
    :class="{ 'filter-tree-dialog': props.isDialog }"
    ref="treeRef"
    node-key="id"
    default-expand-all
    :props="typeState.defaultProps"
    :data="typeState.treeData"
    highlight-current
    :filter-node-method="typeState.filterNode"
    :expand-on-click-node="false"
    @node-click="typeState.handleNodeClick"
  >
    <template #default="{ node, data }">
      <span class="custom-tree-node">
        <span :title="node.label" class="label">
          <jxtech-svg-icon
            :icon="'#icon-File'"
            :size="16"
            class="pointer"
          ></jxtech-svg-icon>
          {{ node.label }}
        </span>
      </span>
    </template>
  </el-tree>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import powerStationPowerInfoApi from "/@/api/base/bean/power-station-power-info";
import { composeTree } from "/@/utils/common";

defineExpose({
  initTreeData: (isChooseRoot: boolean) => {
    return typeState.initTreeData(isChooseRoot);
  },
  getCheckedNode() {
    return treeRef.value.getCurrentNode();
  },
});

let treeRef = ref();
const emit = defineEmits<{
  (e: "handleNodeClick", data: any, node: any, tree: any): void;
}>();
const props = defineProps({
  isDialog: {
    type: Boolean,
    default: false,
  },
});
const typeState = reactive({
  defaultProps: {
    children: "children",
    label: "powerType",
  },
  treeData: [],
  filterText: "",
  filterNode(value: any, data: any) {
    if (!value) return true;
    return data.powerType.indexOf(value) !== -1;
  },
  handleNodeClick(data: any, node?: any, tree?: any) {
    const _self = this;
    if (props.isDialog) {
      // _self.lydata
      //   .callback(JSON.parse(JSON.stringify(data)), node, tree)
      //   .then(() => {
      //     _self.closeDialog();
      //   });
    } else {
      emit("handleNodeClick", JSON.parse(JSON.stringify(data)), node, tree);
    }
  },
  chooseRoot() {
    let rootId = (typeState.treeData[0] as any).id;
    treeRef.value.setCurrentKey(rootId);
    typeState.handleNodeClick(typeState.treeData[0]);
  },
  initTreeData(isChooseRoot: boolean) {
    powerStationPowerInfoApi.queryListTree().then((res: any) => {
      //将结果转换为tree结构
      typeState.treeData = composeTree(res.data, "powerTypeCode", "parentCode");
      if (isChooseRoot) {
        typeState.chooseRoot();
      }
    });
  },
});
watch(
  () => typeState.filterText,
  (val: any) => {
    treeRef.value.filter(val);
  }
);
onMounted(() => {
  typeState.initTreeData(true);
});
</script>

<style lang="scss" scoped>
.filter-tree-dialog {
  height: calc(100vh - 374px);
  overflow: auto;
}
</style>